package com.ht.pms.core.controller.salarySheet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.ht.pms.core.dto.send.NoticeEmailRecordDto;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ht.pms.core.common.constant.SalaryConstants;
import com.ht.pms.core.common.constant.SalaryTemplateTableEnum;
import com.ht.pms.core.dao.SalarySheetManagementDao;
import com.ht.pms.core.dao.SalaryTemplateDao;
import com.ht.pms.core.dao.SalaryUploadFileDao;
import com.ht.pms.core.dto.DeleteSalaryReq;
import com.ht.pms.core.dto.PageResult;
import com.ht.pms.core.dto.Result;
import com.ht.pms.core.dto.SalarySheetQueryReq;
import com.ht.pms.core.dto.UpdateSalaryReq;
import com.ht.pms.core.dto.tempalte.Template;
import com.ht.pms.core.dto.upload.UploadFile;
import com.ht.pms.core.service.SalarySheetManagementService;

/**
 * @author:喻尊龙
 * @date: 2018/4/12
 */
//@CrossOrigin
@RestController
@RequestMapping("/salarySheet")
public class SalarySheetManagementController {

    private Logger logger = LoggerFactory.getLogger(SalarySheetManagementController.class);

    @Autowired
    private SalarySheetManagementService salarySheetManagementService;
    @Autowired
    private SalarySheetManagementDao salarySheetManagementDao;
    @Autowired
    private SalaryUploadFileDao salaryUploadFileDao;
    @Autowired
    private SalaryTemplateDao salaryTemplateDao;

    private String templateCode;
    private String batchCode;
    private String type ;

    /**
     * 通过模板名称获取需要展示的列名
     * @param templateCode
     * @return
     */
    @RequestMapping("/getTableColum")
    @ResponseBody
    public Result getTableColum(@RequestParam("templateCode") String templateCode,@RequestParam("queryType") String queryType,String batchCode){
        logger.error("=====>>>传入的参数为：{{}}",templateCode);
        Result result = Result.buildSuccess();
        List<UploadFile> uploadFiles = null;
        type = "1";//0：初始化查询  1：带参数查询
        if(StringUtils.isBlank(templateCode)){
            try {
                type = "0";
                uploadFiles = salarySheetManagementDao.getUploadFiles("","");
                if(uploadFiles != null && uploadFiles.size()>0){
                    templateCode = uploadFiles.get(0).getTemplateCode();
                    this.templateCode = templateCode;
                    this.batchCode = uploadFiles.get(0).getBatchCode();
                }else {
                    result = Result.buildFail("未找到有效的模板");
                    return result;
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                result = Result.buildFail("数据库操作异常:"+e.getMessage());
                return result;
            }
        }
        List<Map<String,String>> mapList = null;
        Map<String,Object> map = new HashMap<>();
        try {
            if(StringUtils.isBlank(batchCode)){
                batchCode = this.batchCode;
            }
            mapList = salarySheetManagementService.getSalaryTableColum(templateCode,queryType,batchCode);
            UploadFile file =  salarySheetManagementDao.getUploadFileByBatchCode(batchCode);
            this.templateCode = templateCode;
            map.put("data",mapList);
            map.put("type",type);
            map.put("templateCode",templateCode);
            map.put("time",file.getTime() ==null ? null : file.getTime()  );
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            result = Result.buildFail("数据库操作异常:"+e.getMessage());
            return result;
        }
        result = Result.buildSuccess(map);
        return result;
    }

    /**
     * 获取表格数据
     * @param request
     * @return
     */
    @RequestMapping("/getSalaryTableData")
    @ResponseBody
    public PageResult getSalaryTableData(SalarySheetQueryReq request) throws ParseException {
        logger.error("=====>>>传入的参数为：{{}}",request);
        if(StringUtils.isBlank(request.getTemplateCode())){
            request.setTemplateCode(templateCode);
            request.setBatchCode(batchCode);
        }
        String time="";
        if(StringUtils.isNotBlank(request.getPaydayTimeYear())){
            String payDayTime = request.getPaydayTimeYear();
            String dataRegex = "^(\\d{4})-(\\d{2})$";
            boolean match = payDayTime.matches(dataRegex);
            if(!match){
                SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH);
                Date d = sf.parse(request.getPaydayTimeYear().substring(0,16));
                time = new SimpleDateFormat("yyyy-MM").format(d);
            }else {
                time = request.getPaydayTimeYear();
            }

            UploadFile uploadFile = salarySheetManagementDao.getUploadFile(request.getTemplateCode(),time);
            if(uploadFile != null){
                request.setBatchCode(uploadFile.getBatchCode());
            }
        }


        List<Map<String,Object>> mapList = null;
        int count = 0;
        try {
            Map<String,String> sqlMap = salarySheetManagementService.getSalaryTableDataSql(request);
            String countSql = "";
            String dataSql = "";
            if(sqlMap != null){
                countSql = sqlMap.get("countSql");
                dataSql = sqlMap.get("dataSql");
            }
            mapList = salarySheetManagementService.getSalaryTableData(dataSql);
            count = salarySheetManagementService.getSalaryTableDataCount(countSql);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return PageResult.success(mapList,count);
    }

    /**
     * 确认错误数据
     * @param fileId
     * @param jonCode
     * @return
     */
    @RequestMapping("/confirmData")
    @ResponseBody
    public Result confirmData(@RequestParam("fileId") String fileId,@RequestParam("jobCode") String jobCode,@RequestParam("templateCode") String templateCode){
        String tableName = "";
        if("MB2018042701".equals(templateCode)){
            //考勤模板
            tableName = "t_dict_record_a";
        }
        if("MB2018042702".equals(templateCode)){
            // 工资模板
            tableName = "t_dict_record_b";
        }
        salaryUploadFileDao.confirmData(fileId,jobCode,tableName);
        return Result.buildSuccess();
    }


    /**
     * 删除
     * @param reqs
     * @return
     */
    @RequestMapping("/deleteSalaryData")
    @ResponseBody
    public Result deleteSalaryData(@RequestBody DeleteSalaryReq reqs){
        System.out.println("success");
        try {
            reqs.setTemplateCode(templateCode);
            salarySheetManagementDao.deleteSalaryData(reqs);

            int fileId = Integer.parseInt(reqs.getParams().get(0).getFile_id());
            Template template = salaryTemplateDao.selectTemplateByTemplateCode(reqs.getTemplateCode());

            String tableName = SalaryTemplateTableEnum.getByTemplateType(template.getTemplateType()).getRelationTable();

            int successNumber = salaryUploadFileDao.selectSalaryFileRecord(fileId, tableName, SalaryConstants.SALARY_YES);
            int failNumber = salaryUploadFileDao.selectSalaryFileRecord(fileId, tableName, SalaryConstants.SALARY_NO);

            salaryUploadFileDao.updateSalaryFileRecord(successNumber, failNumber, fileId);

        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return Result.buildFail().msg(e.getMessage());
        }

        return Result.buildSuccess();
    }

    @RequestMapping("/updataSalary")
    @ResponseBody
    public Result updataSalary(@RequestBody UpdateSalaryReq req){
        Result result = Result.buildSuccess();
        String fileName = req.getFieldName();
        try {
            result = salarySheetManagementService.updateSalaryData(req);
            //修改成功后，修改日志表状态
            salarySheetManagementDao.updataUploadFileLogState(req.getFileId(),req.getBatchCode(),fileName,req.getJobCode());
            //判断该行是否全部修改完毕，后修改base in_state
            int count = salarySheetManagementDao.queryNotRepairLogCount(req.getFileId());
            if(count == 0){
                //TODO
//                salarySheetManagementDao.updataBase(req.getBatchCode(),req.getFileId());
            }
        } catch (Exception e) {
            result = Result.buildFail().msg(e.getMessage());
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    
    @RequestMapping("/validateUpdataSalary")
    @ResponseBody
    public Result validateUpdataSalary(@RequestBody UpdateSalaryReq req){
        Result result = Result.buildSuccess();
        try {
            result = salarySheetManagementService.validateUpdataSalary(req);
        } catch (Exception e) {
            result = Result.buildFail().msg(e.getMessage());
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/updateFinalState")
    @ResponseBody
    public Result updateFinalState(String batchCode,String templateCode){
        Result result = Result.buildSuccess();
        try {
            salarySheetManagementDao.updateFinalState(batchCode,templateCode);
        } catch (Exception e) {
            result = Result.buildFail().msg(e.getMessage());
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

}
